$(function(){

    $( "#addGame" ).click(function(){

        modalWindowHandler.setWindowPosition('top');
        modalWindowHandler.setModalWindowTitle("Create a New Live Cricket Match");
        modalWindowHandler.setContent('getAddGameForm');
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        //modalWindowHandler.openModalWindow();
        $( "#modalDialogWindow" ).dialog('open');
        //modalWindowHandler.AJAXCallbackFunction = ("setUpAddTeamModalWindow");
        // modalWindowHandler.openModalWindow();
        //setUpAddPlayerModalWindow();
        modalWindowHandler.setWindowWidth('520')
        sendRequest.setAction('getAddGameForm');
        sendRequest.setSendParameters({});
        $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
        {
            $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
            $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
            $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
            $("#mask").empty();
            $(".errorMessageDiv").hide();
            $("#modalDialogWindow").dialog( "option", "buttons", {
                "Back": function() {
                },
                "Next": function() {


                },
                "Cancel": function() {
                    $("#modalDialogWindow").dialog('close');
                    jQuery('.errorMessageDiv').html('');
                }
            });
            setUpGameInsertGameModalWindow()
        });

    });

});


function setUpGameInsertGameModalWindow()
{
    //    $('.errorMessageDiv').show();
    $( "#selectable-teamHome" ).selectable({
        stop: function() {
            $( ".ui-selected", this ).each(function() {
                var index = $( "#selectable-teamHome li" ).index( this );
                var teamName = $(this).text();

                $("#selectable-teamAway .ui-selected").each( function() {
                          
                    if($(this).text() == teamName) {

                        $('#selectable-teamAway .ui-selected').removeClass('ui-selected');
                    }
                });

            });
        }
    });
                
    $( "#selectable-teamAway" ).selectable({
        stop: function() {
            $( ".ui-selected", this ).each(function() {
                var index = $( "#selectable-teamAway li" ).index( this );
                var teamName = $(this).text();
                $("#selectable-teamHome .ui-selected").each( function() {

                    if($(this).text() == teamName) {
                        $('#selectable-teamHome .ui-selected').removeClass('ui-selected');
                    }
                });
            });
        }
    });



    $(".ui-dialog-buttonpane button:contains('Back')").button({
        disabled: true
    });
    $( ".errorMessageDiv" ).hide();
    $(".ui-dialog-buttonpane button:contains('Next')").click(function(){
        var matchName = jQuery(':input[id=matchName]');
        var matchType = jQuery('#matchType option:selected');
        var matchVenue = jQuery(':input[id=matchVenue]');
        var firstEmpire = jQuery(':input[id=firstEmpire]');
        var secondEmpire = jQuery(':input[id=secondEmpire]');
        var thirdEmpire = jQuery(':input[id=thirdEmpire]');
        var reserveEmpire = jQuery(':input[id=reserveEmpire]');
        var matchReferee = jQuery(':input[id=matchReferee]');
        var homeTeam = $("#selectable-teamHome .ui-selected");
        var awayTeam = $("#selectable-teamAway .ui-selected");
        var homeTeamContainer = $('#teamsHomeSelectContainers');
        var awayTeamContainer = $('#teamsAwaySelectContainers');

        var allFields = jQuery([]).add(matchName).add(matchType).add(matchVenue).add(firstEmpire).add(secondEmpire).add(thirdEmpire).add(reserveEmpire).add(matchReferee).add(homeTeam).add(awayTeam).add(homeTeamContainer).add(awayTeamContainer);

        var bValid = true;
        allFields.removeClass('ui-state-error');

        bValid = bValid && formValidator.checkLength(matchName,"your match name",2,100);
        bValid = bValid && formValidator.checkRegexp(matchName,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The match name field only allows alphanumeric characters (a-z 0-9).");
        bValid = bValid && formValidator.checkLength(matchType,"your matchType",2,50);
        bValid = bValid && formValidator.checkRegexp(matchType,/^([0-9a-zA-Z])+$/,"The match type dropdown field only allows alphanumeric characters (a-z 0-9).");
        bValid = bValid && formValidator.checkLength(matchVenue,"your match venue",5,100);
        bValid = bValid && formValidator.checkRegexp(matchVenue,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The match venue field only allows alphanumeric characters (a-z 0-9).");
        bValid = bValid && formValidator.checkLength(firstEmpire,"the first umpire",5,100);
        bValid = bValid && formValidator.checkRegexp(firstEmpire,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The first umpire field only allows alphanumeric characters (a-z 0-9).");
        bValid = bValid && formValidator.checkLength(secondEmpire,"the second umpire",5,100);
        bValid = bValid && formValidator.checkRegexp(secondEmpire,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The second umpire field only allows alphanumeric characters (a-z 0-9).");
        bValid = bValid && formValidator.checkLength(thirdEmpire,"the third umpire",5,100);
        bValid = bValid && formValidator.checkRegexp(thirdEmpire,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The third umpire field only allows alphanumeric characters (a-z 0-9).");
        bValid = bValid && formValidator.checkLength(reserveEmpire,"the reserve umpire",5,100);
        bValid = bValid && formValidator.checkRegexp(reserveEmpire,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The reserve umpire field only allows alphanumeric characters (a-z 0-9).");
        bValid = bValid && formValidator.checkLength(matchReferee,"the match referee",5,100);
        bValid = bValid && formValidator.checkRegexp(matchReferee,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The match referee field only allows alphanumeric characters (a-z 0-9).");


        if (!teamIsSelected("Home"))
        {
            formValidator.updateErrorMessage("Home Team is not seletected. Please select one home team.");
            homeTeamContainer.addClass('ui-state-error');
            bValid= false;
        }

        if (!teamIsSelected("Away"))
        {
            formValidator.updateErrorMessage("Away Team is not seletected. Please select one away team.");
            awayTeamContainer.addClass('ui-state-error');
            bValid= false;
        }
        if (bValid)
        {
            $( ".errorMessageDiv" ).hide();
            postVars = {
                'homeTeamName': homeTeam.text(),
                'homeTeamID': homeTeam.attr('name'),
                'awayTeamID': awayTeam.attr('name'),
                'awayTeamName': awayTeam.text()
            };

            sendRequest.setAction('getMatchTossForm');
            sendRequest.setSendParameters(postVars);
            var hiddenResponseDiv = $('#matchTossDataContainer');
            $(".ui-dialog-buttonpane button:contains('Next')").unbind();
            hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                hiddenResponseDiv.unbind();
                hiddenResponseDiv.hide();
                               
                //$( "#modalDialogWindow" ).children("#modalWindowContent").append('<div id="deleteConfirmation"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>The selected player will be permanently deleted and cannot be recovered. Additionally, all statistics for this player will be deleted as well. Are you sure you want delete this player?</p></div>');
                $('#container_batFirstTeam').buttonset();
                jQuery('#container_batFirstTeam .ui-button').css('width','130px');
                $(".ui-dialog-buttonpane button:contains('Back')").button({
                    disabled: false
                });
                $("#deleteConfirmation").hide();
                                         
                $('#gameMetaDataFromContainer').hide('blind',{},1000);
                hiddenResponseDiv.delay(1200).fadeIn('slow');
                $( "#modalDialogWindow" ).dialog( "option", "title", 'Match Toss Information');
                $( ".errorMessageDiv" ).hide();
            });
            $(".ui-dialog-buttonpane button:contains('Next')").children('span').text('Create New Match');
            $(".ui-dialog-buttonpane button:contains('Create New Match')").click(function(){
                //  $(".ui-dialog-buttonpane button:contains('Create New Match')").unbind();
                var batFirst = $("input:radio[name=batFirstTeam]:checked");
                var tossCommentary = jQuery(':input[id=tossCommentary]');
                batFirst.button( "option", "label" )

                var bValid = true;
                tossCommentary.removeClass('ui-state-error');

                bValid = bValid && formValidator.checkLength(tossCommentary,"the match toss commentary",5,100);
                bValid = bValid && formValidator.checkRegexp(tossCommentary,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The match toss commentary field only allows alphanumeric characters (a-z 0-9).");
                if (bValid)
                {
                    var finalPostVars ={
                        'matchName':matchName.val(),
                        'matchType':matchType.val(),
                        'matchVenue':matchVenue.val(),
                        'firstEmpire':firstEmpire.val(),
                        'secondEmpire':secondEmpire.val(),
                        'thirdEmpire':thirdEmpire.val(),
                        'reserveEmpire':reserveEmpire.val(),
                        'matchReferee':matchReferee.val(),
                        'homeTeamID':homeTeam.attr('name'),
                        'awayTeamID':awayTeam.attr('name'),
                        'homeTeamName':homeTeam.text(),
                        'awayTeamName':awayTeam.text(),
                        'batFirstTeamID': batFirst.val(),
                        'batFirstTeamName': batFirst.button( "option", "label" ),
                        'tossCommentary':tossCommentary.val()
                    };
                               
                }
                sendRequest.setAction('registerNewMatch');
                sendRequest.setSendParameters(finalPostVars);

                var hiddenResponseDiv = jQuery('.responseDiv');
                hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                    hiddenResponseDiv.unbind();
                    hiddenResponseDiv.show();
                    var insertionResponse = (hiddenResponseDiv.html()).replace(/^\s*|\s*$/g,'');
                    // hiddenResponseDiv.html(registrationResponse).show();
                    hiddenResponseDiv.unbind();
                    if (formValidator.hasNumbers(insertionResponse))
                    {
                        $("#modalDialogWindow").dialog('close');
                        jQuery('.errorMessageDiv').html('');
                        GameID = insertionResponse;
                        initPlayerInsertToGameWindow();

                    }
                    else
                    {

                        formValidator.updateErrorMessage("Insertion of new match has failed. Match title already exists. Please insert a unique match title.");
                    }
                });

            });
                             
        }

                       

    });

    setUpBackButtonFunctionality();
}


function setUpBackButtonFunctionality()
{
    $(".ui-dialog-buttonpane button:contains('Back')").click(function(){
        $(".ui-dialog-buttonpane button:contains('Back')").unbind();
        $( ".errorMessageDiv" ).hide();
        $('#matchTossDataContainer').hide('blind',{},500);
        $("#gameMetaDataFromContainer").delay(600).fadeIn('slow');
        $(".ui-dialog-buttonpane button:contains('Back')").button({
            disabled: true
        });
        $( "#modalDialogWindow" ).dialog( "option", "title", 'Insert Match Data');
        $(".ui-dialog-buttonpane button:contains('Create New Match')").unbind();
        $(".ui-dialog-buttonpane button:contains('Create New Match')").children('span').text('Next');
        $( ".errorMessageDiv" ).hide();
        setUpGameInsertGameModalWindow();
    });
}

function teamIsSelected(type)
{
    //         $(".selectableDeletePlayerClass").each( function() {
    //    $( ".errorMessageDiv" ).append($(this).text());
    if ($('#selectable-team'+type+' .ui-selected').hasClass('ui-selected')) {

        //#elm has the class

        return true;
    } else {
        //#elm doesn't have the class
        return false;
    }
//               });
//  return false;
}

